<script setup lang="ts">
  import { useGetAddressList, useReturnFactoryModuleForm } from '@/services/pages/return-factory'
  import useGetEnterprisePersonOptions from '@/services/pages/common/specify-person-options'
  import { ref } from 'vue'
  import { FormInstance } from 'element-plus'
  import _ from 'lodash'
  import { watch } from 'vue'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'

  const { addressList, getAddressListLoading, getAddressListKeyword, getAddressList } =
    useGetAddressList()
  const {
    form,
    getFormLoading,
    returnFactoryModuleSaveLoading,
    getForm,
    resetForm,
    returnFactoryModuleSave,
  } = useReturnFactoryModuleForm()
  const {
    specifyPersonOptions,
    getSpecifyPersonOptionsLoading,
    getSpecifyPersonOptionsKeyword,
    getSpecifyPersonOptions,
  } = useGetEnterprisePersonOptions()

  defineOptions({
    name: 'ReturnFactoryModuleModal',
  })

  const props = defineProps({
    moduleId: {
      type: String,
      default: () => '',
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 表单校验规则
  const rules = ref({
    name: [{ required: true, message: '请输入模块名称', trigger: ['blur', 'change'] }],
    status: [{ required: true, message: '模块状态不能为空', trigger: ['blur', 'change'] }],
    mobileShow: [{ required: true, message: '移动端显示不能为空', trigger: ['blur', 'change'] }],
    repairCheckRoot: [
      { required: true, message: '请选择返厂审核权限', trigger: ['blur', 'change'] },
    ],
    repairCheckRootEmpIds: [
      { required: true, message: '请选择返厂审核人员', trigger: ['blur', 'change'] },
    ],
    repairCheckType: [
      { required: true, message: '请选择返厂审核方式', trigger: ['blur', 'change'] },
    ],
    enabledFault: [
      { required: true, message: '请选择新建返厂单时故障库的状态', trigger: ['blur', 'change'] },
    ],
    enabledSnCodeCheck: [
      { required: true, message: '序列号/序列号校验不能为空', trigger: ['blur', 'change'] },
    ],
    enabledFirstSendAfterIncom: [
      { required: true, message: '允许先发后收不能为空', trigger: ['blur', 'change'] },
    ],
    sureFee: [{ required: true, message: '确认费用不能为空', trigger: ['blur', 'change'] }],
    enabledCheckProcess: [
      { required: true, message: '检测单流程不能为空', trigger: ['blur', 'change'] },
    ],
    enabledServiceReport: [
      { required: true, message: '检测报告不能为空', trigger: ['blur', 'change'] },
    ],
    enableRepairSignFor: [
      { required: true, message: '返厂签收不能为空', trigger: ['blur', 'change'] },
    ],
    enableWriteLogistics: [
      { required: true, message: '物流填写不能为空', trigger: ['blur', 'change'] },
    ],
    repairAddrStoreId: [
      { required: false, message: '请选择默认返厂地址', trigger: ['change', 'blur'] },
    ],
  })
  const formInstance = ref<FormInstance | null>(null)

  /**
   * 选择部门更新事件
   */
  const handleEnableNetworkChange = (val: boolean) => {
    rules.value.repairAddrStoreId[0].required = true

    if (!val) {
      rules.value.repairAddrStoreId[0].required = true
    }
  }

  const onCancel = () => {
    resetForm()
    visible.value = false
  }

  const onConfirm = async () => {
    if (formInstance.value) {
      try {
        await formInstance.value.validate()
        const res = await returnFactoryModuleSave()
        if (res.code === 20000) {
          HMessage.success(infoTip.returnFactory.module.save_success)
          visible.value = false
          resetForm()
          emits('update')
          return
        }

        HMessageBox.error(infoTip.returnFactory.module.errCode[res.code] || res.message)
      } catch (e) {
        // e
      }
    }
  }

  const handleGetAddressList = _.debounce((keyword: string) => {
    if (keyword !== getAddressListKeyword.value) {
      getAddressListKeyword.value = keyword
      getAddressList()
    }
  }, 600)

  const handleGetEnterprisePersonOptions = _.debounce((keyword: string) => {
    if (getSpecifyPersonOptionsKeyword.value !== keyword) {
      getSpecifyPersonOptionsKeyword.value = keyword
      getSpecifyPersonOptions()
    }
  }, 600)

  const handleChangeReturnFactoryCheck = () => {
    if (form.value.repairCheckRoot === 2) {
      getSpecifyPersonOptions()
    }
  }

  watch(
    visible,
    async (value) => {
      if (value) {
        await getAddressList()

        if (props.moduleId) {
          await getForm(props.moduleId)
          handleChangeReturnFactoryCheck()
        }
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    :title="props.moduleId ? '编辑模块' : '添加模块'"
    :width="800"
    unit="px"
    :loading="returnFactoryModuleSaveLoading || getFormLoading"
  >
    <el-form
      ref="formInstance"
      inline-message
      label-position="top"
      :model="form"
      :rules="rules"
      class="modal_form_content"
    >
      <!-- 模块名称 -->
      <el-form-item label="模块名称" prop="name">
        <el-input v-model.trim="form.name" placeholder="请输入模块名称" maxlength="20" />
      </el-form-item>
      <div class="same_line">
        <!-- 模块状态 -->
        <el-form-item label="模块状态" prop="status" class="same_line">
          <div class="switch-container">
            <el-switch
              :model-value="!form.status"
              size="small"
              @change="form.status = !form.status"
            />
            {{ !form.status ? '启用' : '禁用' }}
          </div>
        </el-form-item>

        <!-- 移动端显示 -->
        <el-form-item label="移动端显示" prop="mobileShow" class="same_line">
          <div class="switch-container">
            <el-switch v-model="form.mobileShow" size="small" />
            {{ form.mobileShow ? '显示' : '隐藏' }}
          </div>
        </el-form-item>
      </div>

      <!-- 审核权限 -->
      <el-form-item label="审核权限" prop="repairCheckRoot" class="same_line">
        <el-radio-group v-model="form.repairCheckRoot" @change="handleChangeReturnFactoryCheck">
          <el-radio :value="1">自动审核</el-radio>
          <el-radio :value="2">人工审核</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 审核人员 -->
      <el-form-item v-if="form.repairCheckRoot === 2" label="审核人员" prop="repairCheckRootEmpIds">
        <el-select
          v-model="form.repairCheckRootEmpIds"
          placeholder="请选择返厂审核人员"
          :loading="getSpecifyPersonOptionsLoading"
          filterable
          :filter-method="handleGetEnterprisePersonOptions"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="5"
        >
          <el-option
            v-for="(enterprisePerson, enterprisePersonIndex) in specifyPersonOptions"
            :key="enterprisePersonIndex"
            :value="enterprisePerson.id"
            :label="enterprisePerson.name"
          />
        </el-select>
      </el-form-item>

      <!-- 审核方式 -->
      <el-form-item label="审核方式" prop="repairCheckType" class="same_line">
        <el-radio-group v-model="form.repairCheckType">
          <el-radio :value="1">按整单审核</el-radio>
          <el-radio :value="2">单独审核</el-radio>
        </el-radio-group>
      </el-form-item>

      <div class="same_line">
        <!--选择部门-->
        <el-form-item label="选择部门" prop="" class="same_line">
          <div class="switch-container">
            <el-switch
              v-model="form.enabledNetwork"
              size="small"
              @change="handleEnableNetworkChange"
            />
            {{ form.enabledNetwork ? '允许选择' : '不允许选择' }}
          </div>
        </el-form-item>

        <!-- 填写物流 -->
        <el-form-item label="物流填写" class="same_line" prop="enableWriteLogistics">
          <div class="switch-container">
            <el-switch v-model="form.enableWriteLogistics" size="small" />
            {{ form.enableWriteLogistics ? '开启' : '关闭' }}
          </div>
        </el-form-item>
      </div>

      <!-- 默认返厂地址 -->
      <el-form-item label="默认返厂地址" prop="repairAddrStoreId">
        <el-select
          v-model="form.repairAddrStoreId"
          :loading="getAddressListLoading"
          placeholder="联系人姓名/手机号"
          filterable
          :filter-method="handleGetAddressList"
          :disabled="form.enabledNetwork"
        >
          <el-option
            v-for="(address, addressIndex) in addressList"
            :key="addressIndex"
            :label="`${address.username} ${address.phone} ${address.province} ${address.area} ${address.city} ${address.address}`"
            :value="address.id"
          >
            {{
              `${address.username} ${address.phone} ${address.province} ${address.area} ${address.city} ${address.address}`
            }}
          </el-option>
        </el-select>
      </el-form-item>

      <div class="same_line">
        <!-- 返厂签收 -->
        <el-form-item label="返厂签收" class="same_line" prop="enableRepairSignFor">
          <div class="switch-container">
            <el-switch v-model="form.enableRepairSignFor" size="small" />
            {{ form.enableRepairSignFor ? '开启' : '关闭' }}
          </div>
        </el-form-item>
        <!-- 故障库 -->
        <!--先隐藏，后期可能会用到-->
        <!--<el-form-item label="故障库" class="same_line" prop="enabledFault">-->
        <!--  <div class="switch-container">-->
        <!--    <el-switch v-model="form.enabledFault" size="small" />-->
        <!--    <span>{{ form.enabledFault ? '开启' : '关闭' }}</span>-->
        <!--    <el-tooltip effect="dark" content="新建返厂单是否开启故障库" placement="top">-->
        <!--      <i class="iconfont icon-warning"></i>-->
        <!--    </el-tooltip>-->
        <!--  </div>-->
        <!--</el-form-item>-->

        <!-- 序列号/序列号校验 -->
        <el-form-item label="序列号/序列号校验" prop="enabledSnCodeCheck" class="same_line">
          <div class="switch-container">
            <el-switch v-model="form.enabledSnCodeCheck" size="small" />
            <span>{{ form.enabledSnCodeCheck ? '开启' : '关闭' }}</span>
            <el-tooltip
              effect="dark"
              content="开启后，返厂单所有流程的序列号必须一致"
              placement="top"
            >
              <i class="iconfont icon-warning"></i>
            </el-tooltip>
          </div>
        </el-form-item>
      </div>
      <div class="same_line">
        <!-- 允许先发后收 -->
        <el-form-item label="允许先发后收" prop="enabledFirstSendAfterIncom" class="same_line">
          <div class="switch-container">
            <el-switch v-model="form.enabledFirstSendAfterIncom" size="small" />
            <span>{{ form.enabledFirstSendAfterIncom ? '允许' : '禁止' }}</span>
            <el-tooltip effect="dark" content="允许后，可以不签收旧机也可以发新机" placement="top">
              <i class="iconfont icon-warning"></i>
            </el-tooltip>
          </div>
        </el-form-item>

        <!-- 确认费用 -->
        <!--先隐藏，后期可能会用到-->
        <!--<el-form-item label="确认费用" prop="sureFee" class="same_line">-->
        <!--  <div class="switch-container">-->
        <!--    <el-switch v-model="form.sureFee" size="small" />-->
        <!--    <span>{{ form.sureFee ? '开启' : '关闭' }}</span>-->
        <!--    <el-tooltip effect="dark" content="开启后，必选确认费用才允许推送工单" placement="top">-->
        <!--      <i class="iconfont icon-warning"></i>-->
        <!--    </el-tooltip>-->
        <!--  </div>-->
        <!--</el-form-item>-->
        <!-- 检测单流程 -->
        <el-form-item label="检测流程" class="same_line" prop="enabledCheckProcess">
          <div class="switch-container">
            <el-switch v-model="form.enabledCheckProcess" size="small" />
            {{ form.enabledCheckProcess ? '开启' : '关闭' }}
          </div>
        </el-form-item>
      </div>

      <!-- <div class="same_line"> -->
      <!-- 服务报告 -->
      <!--先隐藏，后期可能会用到-->
      <!--<el-form-item label="服务报告" class="same_line" prop="enabledServiceReport">-->
      <!--  <div class="switch-container">-->
      <!--    <el-switch v-model="form.enabledServiceReport" size="small" />-->
      <!--    {{ form.enabledServiceReport ? '开启' : '关闭' }}-->
      <!--  </div>-->
      <!--</el-form-item>-->
      <!-- </div> -->
    </el-form>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="onCancel">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .icon-warning {
    color: $secondColor2;
    line-height: 16px;
    height: 16px;
  }

  .same_line {
    align-items: flex-start !important;

    :deep(.el-form-item__label) {
      line-height: 14px !important;
      height: 14px !important;
    }
  }

  .switch-container {
    display: flex;
    align-items: center;
    height: 16px;
    column-gap: 2px;

    :deep(.el-switch) {
      height: 16px;
    }
  }
</style>
